<template>
  <div class="preview-container" :style="pageStyle">
    <!-- 顶部工具栏 -->
    <div class="preview-toolbar">
      <div class="toolbar-item" @click="backToEditor" title="返回编辑器">
        <span>↩️ 返回编辑器</span>
      </div>
      <div class="toolbar-title">
        {{ pageConfig.title || '未命名页面' }} - 预览模式
      </div>
    </div>
    
    <!-- 预览内容区域 -->
    <div class="preview-content">
      <!-- 渲染组件列表 -->
      <template v-if="pageConfig.components.length > 0">
        <component 
          v-for="(component, index) in pageConfig.components" 
          :key="component.id"
          :is="resolveComponent(component.type)"
          v-bind="resolveComponentProps(component)"
          :style="resolveComponentStyle(component)"
          @click="handleComponentEvent(component, 'click', $event)"
          @change="handleComponentEvent(component, 'change', $event)"
        />
      </template>
      
      <!-- 空状态提示 -->
      <div v-else class="empty-tip">
        <p>当前页面没有任何组件</p>
        <button class="btn primary" @click="backToEditor">返回编辑器添加组件</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import type { PageConfig, ComponentItem } from '@/stores/page'
import { useDataPoolStore } from '@/stores/dataPool'

const router = useRouter()
const dataPoolStore = useDataPoolStore()

// 页面配置
const pageConfig = ref<PageConfig>({
  title: '未命名页面',
  description: '',
  components: [],
  style: {
    backgroundColor: '#f5f5f5',
    width: '100%',
    minHeight: '100%'
  }
})

// 页面样式
const pageStyle = computed(() => {
  return pageConfig.value.style || {}
})

// 加载页面配置
onMounted(() => {
  try {
    const configJson = localStorage.getItem('previewPageConfig')
    if (configJson) {
      pageConfig.value = JSON.parse(configJson)
    }
    
    // 加载数据池配置
    const dataPoolJson = localStorage.getItem('previewDataPool')
    if (dataPoolJson) {
      dataPoolStore.importJSON(dataPoolJson)
    }
  } catch (error) {
    console.error('加载页面配置失败:', error)
  }
})

// 返回编辑器
const backToEditor = () => {
  router.push('/editor')
}

// 根据组件类型解析对应的组件
const resolveComponent = (type: string) => {
  // 这里可以根据组件类型返回对应的组件
  // 实际项目中可能需要动态导入或注册组件
  switch (type) {
    case 'input':
      return 'input'
    case 'select':
      return 'select'
    case 'button':
      return 'button'
    case 'text':
      return 'div'
    case 'container':
      return 'div'
    // 其他组件类型...
    default:
      return 'div'
  }
}

// 解析组件属性（应用数据绑定）
const resolveComponentProps = (component: ComponentItem) => {
  const result = { ...component.props }
  
  // 应用属性的数据绑定
  if (component.dataBindings && component.dataBindings.length > 0) {
    component.dataBindings.forEach(binding => {
      const { propName, dataId } = binding
      
      // 处理普通属性绑定（非样式属性）
      if (!propName.startsWith('style:')) {
        const dataValue = dataPoolStore.getDataItemValue(dataId)
        if (dataValue !== undefined) {
          result[propName] = dataValue
        }
      }
    })
  }
  
  return result
}

// 解析组件样式（应用数据绑定）
const resolveComponentStyle = (component: ComponentItem) => {
  const style = { ...component.style }
  
  // 应用样式属性的数据绑定
  if (component.dataBindings && component.dataBindings.length > 0) {
    component.dataBindings.forEach(binding => {
      const { propName, dataId } = binding
      
      // 处理样式属性绑定
      if (propName.startsWith('style:')) {
        const styleKey = propName.substring(6) // 去掉 'style:' 前缀
        const dataValue = dataPoolStore.getDataItemValue(dataId)
        if (dataValue !== undefined) {
          style[styleKey] = dataValue
        }
      }
    })
  }
  
  return style
}

// 处理组件事件
const handleComponentEvent = (component: ComponentItem, eventName: string, event: any) => {
  // 获取组件的事件处理代码
  const eventHandler = component.events?.[eventName]
  if (!eventHandler) return
  
  try {
    // 创建一个函数来执行事件处理代码
    const fn = new Function('event', 'component', eventHandler)
    fn(event, component)
  } catch (error) {
    console.error(`执行${eventName}事件处理器失败:`, error)
  }
}
</script>

<style lang="scss" scoped>
.preview-container {
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  
  .preview-toolbar {
    height: 50px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    background-color: #fff;
    border-bottom: 1px solid #e0e0e0;
    
    .toolbar-item {
      margin-right: 16px;
      cursor: pointer;
      
      &:hover {
        color: #409eff;
      }
    }
    
    .toolbar-title {
      font-size: 16px;
      font-weight: 500;
      flex: 1;
      text-align: center;
    }
  }
  
  .preview-content {
    flex: 1;
    padding: 20px;
    overflow: auto;
    position: relative;
    
    .empty-tip {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      color: #999;
      
      p {
        margin-bottom: 16px;
      }
    }
  }
}
</style>